

using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;
using System.Collections.Generic;

namespace CoreCms.Net.Web.Admin.Controllers
{
    /// <summary>
    /// 商品一物一码表
    ///</summary>
    [Description("商品一物一码表")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize]
    public class corecmsproductscodeController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IcorecmsproductscodeServices _corecmsproductscodeServices;
        private readonly IdistributorServices _distributorServices;
        private readonly ICoreCmsProductsServices _ProductsServices;
        private readonly ICoreCmsGoodsServices _coreCmsGoodsServices;

        /// <summary>
        /// 构造函数
        ///</summary>
        public corecmsproductscodeController(IWebHostEnvironment webHostEnvironment
            , IcorecmsproductscodeServices corecmsproductscodeServices
            , IdistributorServices distributorServices
            , ICoreCmsProductsServices productsServices
            , ICoreCmsGoodsServices coreCmsGoodsServices

            )
        {

            _webHostEnvironment = webHostEnvironment;
            _corecmsproductscodeServices = corecmsproductscodeServices;
            _distributorServices = distributorServices;
            _ProductsServices = productsServices;
            _coreCmsGoodsServices = coreCmsGoodsServices;

        }

        #region 获取列表============================================================
        // POST: Api/corecmsproductscode/GetPageList
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<corecmsproductscode>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<corecmsproductscode, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                "code" => p => p.code,
                "url" => p => p.url,
                "productsId" => p => p.productsId,
                "count" => p => p.count,
                "userId" => p => p.userId,
                "isState" => p => p.isState,
                "update_time" => p => p.update_time,
                "create_time" => p => p.create_time,
                "isDel" => p => p.isDel,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选

            //一物一码id int
            var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
            //货品码 varchar
            var code = Request.Form["code"].FirstOrDefault();
            if (!string.IsNullOrEmpty(code))
            {
                where = where.And(p => p.code.Contains(code));
            }
            //货品地址+参数 varchar
            var url = Request.Form["url"].FirstOrDefault();
            if (!string.IsNullOrEmpty(url))
            {
                where = where.And(p => p.url.Contains(url));
            }
            //货品id int
            var productsId = Request.Form["productsId"].FirstOrDefault().ObjectToInt(0);
            if (productsId > 0)
            {
                where = where.And(p => p.productsId == productsId);
            }
            //查询次数 int
            var count = Request.Form["count"].FirstOrDefault().ObjectToInt(0);
            if (count > 0)
            {
                where = where.And(p => p.count == count);
            }
            //用户id int
            var userId = Request.Form["userId"].FirstOrDefault().ObjectToInt(0);
            if (userId > 0)
            {
                where = where.And(p => p.userId == userId);
            }
            //兑换状态 0未兑换 1 已兑换 int
            var isState = Request.Form["isState"].FirstOrDefault().ObjectToInt(0);
            if (isState > 0)
            {
                where = where.And(p => p.isState == isState);
            }
            //兑换时间 datetime
            var update_time = Request.Form["update_time"].FirstOrDefault();
            if (!string.IsNullOrEmpty(update_time))
            {
                if (update_time.Contains("到"))
                {
                    var dts = update_time.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.update_time > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.update_time < dtEnd);
                }
                else
                {
                    var dt = update_time.ObjectToDate();
                    where = where.And(p => p.update_time > dt);
                }
            }
            //生成时间 datetime
            var create_time = Request.Form["create_time"].FirstOrDefault();
            if (!string.IsNullOrEmpty(create_time))
            {
                if (create_time.Contains("到"))
                {
                    var dts = create_time.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.create_time > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.create_time < dtEnd);
                }
                else
                {
                    var dt = create_time.ObjectToDate();
                    where = where.And(p => p.create_time > dt);
                }
            }
            ////删除状态 tinyint
            //var isDel = Request.Form["isDel"].FirstOrDefault();
            //         if (!string.IsNullOrEmpty(isDel))
            //         {
            //             where = where.And(p => p.isDel.Contains(isDel));
            //         }
            //获取数据
            var list = await _corecmsproductscodeServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/corecmsproductscode/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };
            return jm;
        }
        #endregion

        #region 创建数据============================================================
        // POST: Api/corecmsproductscode/GetCreate
        /// <summary>
        /// 创建数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public AdminUiCallBack GetCreate()
        {
            var distributor = _distributorServices.QueryAsync();
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };
            jm.data = new
            {
                distributor
            };
            return jm;
        }
        #endregion

        #region 创建提交============================================================
        // POST: Api/corecmsproductscode/DoCreate
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public async Task<AdminUiCallBack> DoCreate([FromBody] corecmsproductscode entity)
        {
            var jm = await _corecmsproductscodeServices.InsertAsync(entity);
            return jm;
        }
        #endregion

        #region 编辑数据============================================================
        // POST: Api/corecmsproductscode/GetEdit
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据")]
        public async Task<AdminUiCallBack> GetEdit([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();
            var distributor = _distributorServices.QueryAsync();
            //返回数据
            var model = await _corecmsproductscodeServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = new
            {
                distributor,
                model
            };

            return jm;
        }
        #endregion

        #region 编辑提交============================================================
        // POST: Api/corecmsproductscode/Edit
        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑提交")]
        public async Task<AdminUiCallBack> DoEdit([FromBody] corecmsproductscode entity)
        {
            var jm = await _corecmsproductscodeServices.UpdateAsync(entity);
            return jm;
        }
        #endregion

        #region 删除数据============================================================
        // POST: Api/corecmsproductscode/DoDelete/10
        /// <summary>
        /// 单选删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("单选删除")]
        public async Task<AdminUiCallBack> DoDelete([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _corecmsproductscodeServices.ExistsAsync(p => p.id == entity.id, true);
            if (!model)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            jm = await _corecmsproductscodeServices.DeleteByIdAsync(entity.id);

            return jm;
        }
        #endregion

        #region 批量删除============================================================
        // POST: Api/corecmsproductscode/DoBatchDelete/10,11,20
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("批量删除")]
        public async Task<AdminUiCallBack> DoBatchDelete([FromBody] FMArrayIntIds entity)
        {
            var jm = await _corecmsproductscodeServices.DeleteByIdsAsync(entity.id);
            return jm;
        }

        #endregion

        #region 预览数据============================================================
        // POST: Api/corecmsproductscode/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _corecmsproductscodeServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = model;

            return jm;
        }
        #endregion

        #region 选择导出============================================================
        // POST: Api/corecmsproductscode/SelectExportExcel/10
        /// <summary>
        /// 选择导出
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("选择导出")]
        public async Task<AdminUiCallBack> SelectExportExcel([FromBody] FMArrayIntIds entity)
        {
            var jm = new AdminUiCallBack();

            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var mySheet = book.CreateSheet("Sheet1");
            //获取list数据
            var listModel = await _corecmsproductscodeServices.QueryListByClauseAsync(p => entity.id.Contains(p.id), p => p.id, OrderByType.Asc, true);
            //给sheet1添加第一行的头部标题
            var headerRow = mySheet.CreateRow(0);
            var headerStyle = ExcelHelper.GetHeaderStyle(book);

            var cell0 = headerRow.CreateCell(0);
            cell0.SetCellValue("一物一码id");
            cell0.CellStyle = headerStyle;
            mySheet.SetColumnWidth(0, 10 * 256);

            var cell1 = headerRow.CreateCell(1);
            cell1.SetCellValue("货品码");
            cell1.CellStyle = headerStyle;
            mySheet.SetColumnWidth(1, 10 * 256);

            var cell2 = headerRow.CreateCell(2);
            cell2.SetCellValue("货品地址+参数");
            cell2.CellStyle = headerStyle;
            mySheet.SetColumnWidth(2, 10 * 256);

            var cell3 = headerRow.CreateCell(3);
            cell3.SetCellValue("货品id");
            cell3.CellStyle = headerStyle;
            mySheet.SetColumnWidth(3, 10 * 256);

            var cell4 = headerRow.CreateCell(4);
            cell4.SetCellValue("查询次数");
            cell4.CellStyle = headerStyle;
            mySheet.SetColumnWidth(4, 10 * 256);

            var cell5 = headerRow.CreateCell(5);
            cell5.SetCellValue("用户id");
            cell5.CellStyle = headerStyle;
            mySheet.SetColumnWidth(5, 10 * 256);

            var cell6 = headerRow.CreateCell(6);
            cell6.SetCellValue("兑换状态 0未兑换 1 已兑换");
            cell6.CellStyle = headerStyle;
            mySheet.SetColumnWidth(6, 10 * 256);

            var cell7 = headerRow.CreateCell(7);
            cell7.SetCellValue("兑换时间");
            cell7.CellStyle = headerStyle;
            mySheet.SetColumnWidth(7, 10 * 256);

            var cell8 = headerRow.CreateCell(8);
            cell8.SetCellValue("生成时间");
            cell8.CellStyle = headerStyle;
            mySheet.SetColumnWidth(8, 10 * 256);

            var cell9 = headerRow.CreateCell(9);
            cell9.SetCellValue("删除状态");
            cell9.CellStyle = headerStyle;
            mySheet.SetColumnWidth(9, 10 * 256);

            headerRow.Height = 30 * 20;
            var commonCellStyle = ExcelHelper.GetCommonStyle(book);

            //将数据逐步写入sheet1各个行
            for (var i = 0; i < listModel.Count; i++)
            {
                var rowTemp = mySheet.CreateRow(i + 1);

                var rowTemp0 = rowTemp.CreateCell(0);
                rowTemp0.SetCellValue(listModel[i].id.ToString());
                rowTemp0.CellStyle = commonCellStyle;

                var rowTemp1 = rowTemp.CreateCell(1);
                rowTemp1.SetCellValue(listModel[i].code.ToString());
                rowTemp1.CellStyle = commonCellStyle;

                var rowTemp2 = rowTemp.CreateCell(2);
                rowTemp2.SetCellValue(listModel[i].url.ToString());
                rowTemp2.CellStyle = commonCellStyle;

                var rowTemp3 = rowTemp.CreateCell(3);
                rowTemp3.SetCellValue(listModel[i].productsId.ToString());
                rowTemp3.CellStyle = commonCellStyle;

                var rowTemp4 = rowTemp.CreateCell(4);
                rowTemp4.SetCellValue(listModel[i].count.ToString());
                rowTemp4.CellStyle = commonCellStyle;

                var rowTemp5 = rowTemp.CreateCell(5);
                rowTemp5.SetCellValue(listModel[i].userId.ToString());
                rowTemp5.CellStyle = commonCellStyle;

                var rowTemp6 = rowTemp.CreateCell(6);
                rowTemp6.SetCellValue(listModel[i].isState.ToString());
                rowTemp6.CellStyle = commonCellStyle;

                var rowTemp7 = rowTemp.CreateCell(7);
                rowTemp7.SetCellValue(listModel[i].update_time.ToString());
                rowTemp7.CellStyle = commonCellStyle;

                var rowTemp8 = rowTemp.CreateCell(8);
                rowTemp8.SetCellValue(listModel[i].create_time.ToString());
                rowTemp8.CellStyle = commonCellStyle;

                var rowTemp9 = rowTemp.CreateCell(9);
                rowTemp9.SetCellValue(listModel[i].isDel.ToString());
                rowTemp9.CellStyle = commonCellStyle;

            }
            // 导出excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-corecmsproductscode导出(选择结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion

        #region 查询导出============================================================
        // POST: Api/corecmsproductscode/QueryExportExcel/10
        /// <summary>
        /// 查询导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("查询导出")]
        public async Task<AdminUiCallBack> QueryExportExcel()
        {
            var jm = new AdminUiCallBack();

            var where = PredicateBuilder.True<corecmsproductscode>();
            //查询筛选

            //一物一码id int
            var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
            //货品码 varchar
            var code = Request.Form["code"].FirstOrDefault();
            if (!string.IsNullOrEmpty(code))
            {
                where = where.And(p => p.code.Contains(code));
            }
            //货品地址+参数 varchar
            var url = Request.Form["url"].FirstOrDefault();
            if (!string.IsNullOrEmpty(url))
            {
                where = where.And(p => p.url.Contains(url));
            }
            //货品id int
            var productsId = Request.Form["productsId"].FirstOrDefault().ObjectToInt(0);
            if (productsId > 0)
            {
                where = where.And(p => p.productsId == productsId);
            }
            //查询次数 int
            var count = Request.Form["count"].FirstOrDefault().ObjectToInt(0);
            if (count > 0)
            {
                where = where.And(p => p.count == count);
            }
            //用户id int
            var userId = Request.Form["userId"].FirstOrDefault().ObjectToInt(0);
            if (userId > 0)
            {
                where = where.And(p => p.userId == userId);
            }
            //兑换状态 0未兑换 1 已兑换 int
            var isState = Request.Form["isState"].FirstOrDefault().ObjectToInt(0);
            if (isState > 0)
            {
                where = where.And(p => p.isState == isState);
            }
            //兑换时间 datetime
            var update_time = Request.Form["update_time"].FirstOrDefault();
            if (!string.IsNullOrEmpty(update_time))
            {
                var dt = update_time.ObjectToDate();
                where = where.And(p => p.update_time > dt);
            }
            //生成时间 datetime
            var create_time = Request.Form["create_time"].FirstOrDefault();
            if (!string.IsNullOrEmpty(create_time))
            {
                var dt = create_time.ObjectToDate();
                where = where.And(p => p.create_time > dt);
            }
            ////删除状态 tinyint
            //var isDel = Request.Form["isDel"].FirstOrDefault();
            //         if (!string.IsNullOrEmpty(isDel))
            //         {
            //             where = where.And(p => p.isDel.Contains(isDel));
            //         }
            //获取数据
            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var mySheet = book.CreateSheet("Sheet1");
            //获取list数据
            var listModel = await _corecmsproductscodeServices.QueryListByClauseAsync(where, p => p.id, OrderByType.Asc, true);
            //给sheet1添加第一行的头部标题
            var headerRow = mySheet.CreateRow(0);
            var headerStyle = ExcelHelper.GetHeaderStyle(book);

            var cell0 = headerRow.CreateCell(0);
            cell0.SetCellValue("一物一码id");
            cell0.CellStyle = headerStyle;
            mySheet.SetColumnWidth(0, 10 * 256);

            var cell1 = headerRow.CreateCell(1);
            cell1.SetCellValue("货品码");
            cell1.CellStyle = headerStyle;
            mySheet.SetColumnWidth(1, 10 * 256);

            var cell2 = headerRow.CreateCell(2);
            cell2.SetCellValue("货品地址+参数");
            cell2.CellStyle = headerStyle;
            mySheet.SetColumnWidth(2, 10 * 256);

            var cell3 = headerRow.CreateCell(3);
            cell3.SetCellValue("货品id");
            cell3.CellStyle = headerStyle;
            mySheet.SetColumnWidth(3, 10 * 256);

            var cell4 = headerRow.CreateCell(4);
            cell4.SetCellValue("查询次数");
            cell4.CellStyle = headerStyle;
            mySheet.SetColumnWidth(4, 10 * 256);

            var cell5 = headerRow.CreateCell(5);
            cell5.SetCellValue("用户id");
            cell5.CellStyle = headerStyle;
            mySheet.SetColumnWidth(5, 10 * 256);

            var cell6 = headerRow.CreateCell(6);
            cell6.SetCellValue("兑换状态 0未兑换 1 已兑换");
            cell6.CellStyle = headerStyle;
            mySheet.SetColumnWidth(6, 10 * 256);

            var cell7 = headerRow.CreateCell(7);
            cell7.SetCellValue("兑换时间");
            cell7.CellStyle = headerStyle;
            mySheet.SetColumnWidth(7, 10 * 256);

            var cell8 = headerRow.CreateCell(8);
            cell8.SetCellValue("生成时间");
            cell8.CellStyle = headerStyle;
            mySheet.SetColumnWidth(8, 10 * 256);

            var cell9 = headerRow.CreateCell(9);
            cell9.SetCellValue("删除状态");
            cell9.CellStyle = headerStyle;
            mySheet.SetColumnWidth(9, 10 * 256);


            headerRow.Height = 30 * 20;
            var commonCellStyle = ExcelHelper.GetCommonStyle(book);

            //将数据逐步写入sheet1各个行
            for (var i = 0; i < listModel.Count; i++)
            {
                var rowTemp = mySheet.CreateRow(i + 1);


                var rowTemp0 = rowTemp.CreateCell(0);
                rowTemp0.SetCellValue(listModel[i].id.ToString());
                rowTemp0.CellStyle = commonCellStyle;



                var rowTemp1 = rowTemp.CreateCell(1);
                rowTemp1.SetCellValue(listModel[i].code.ToString());
                rowTemp1.CellStyle = commonCellStyle;



                var rowTemp2 = rowTemp.CreateCell(2);
                rowTemp2.SetCellValue(listModel[i].url.ToString());
                rowTemp2.CellStyle = commonCellStyle;



                var rowTemp3 = rowTemp.CreateCell(3);
                rowTemp3.SetCellValue(listModel[i].productsId.ToString());
                rowTemp3.CellStyle = commonCellStyle;



                var rowTemp4 = rowTemp.CreateCell(4);
                rowTemp4.SetCellValue(listModel[i].count.ToString());
                rowTemp4.CellStyle = commonCellStyle;



                var rowTemp5 = rowTemp.CreateCell(5);
                rowTemp5.SetCellValue(listModel[i].userId.ToString());
                rowTemp5.CellStyle = commonCellStyle;



                var rowTemp6 = rowTemp.CreateCell(6);
                rowTemp6.SetCellValue(listModel[i].isState.ToString());
                rowTemp6.CellStyle = commonCellStyle;



                var rowTemp7 = rowTemp.CreateCell(7);
                rowTemp7.SetCellValue(listModel[i].update_time.ToString());
                rowTemp7.CellStyle = commonCellStyle;



                var rowTemp8 = rowTemp.CreateCell(8);
                rowTemp8.SetCellValue(listModel[i].create_time.ToString());
                rowTemp8.CellStyle = commonCellStyle;



                var rowTemp9 = rowTemp.CreateCell(9);
                rowTemp9.SetCellValue(listModel[i].isDel.ToString());
                rowTemp9.CellStyle = commonCellStyle;


            }
            // 写入到excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-corecmsproductscode导出(查询结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion


        // POST: Api/corecmsproductscode/QueryExportExcelCode
        /// <summary>
        /// 生成积分兑换码并导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("生成积分兑换码导出")]
        public async Task<AdminUiCallBack> QueryExportExcelCode([FromBody] FMProductCode entity)
        {
            var jm = new AdminUiCallBack();

            if (entity.Count > 0)
            {
                List<corecmsproductscode> listModel = new List<corecmsproductscode>();
                Random rand = new Random();
                for (int i = 0; i < entity.Count; i++)
                {
                    var model = new corecmsproductscode();
                    //生成随机code
                    model.code = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.服务券兑换码) + CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.订单编号) + CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.提货单号);
                    model.url = AppSettingsHelper.GetContent("AppConfig", "WxOpenUrl") + model.code;
                    model.productsId = entity.ProductId;
                    model.count = 0;
                    model.userId = 0;
                    model.isState = 0;
                    model.create_time = DateTime.Now;
                    model.d_id = entity.DistributorId;
                    listModel.Add(model);
                }
                CoreCmsGoods Goods = new  CoreCmsGoods();
              var ProductModel = _ProductsServices.QueryById(entity.ProductId);
                if (ProductModel.goodsId > 0) {
                      Goods = _coreCmsGoodsServices.QueryById(ProductModel.goodsId);
                }
                var modedistributor = _distributorServices.QueryById(entity.DistributorId);
                var ret = await _corecmsproductscodeServices.BulkInsert(listModel);
                if (ret.code == 0)
                {

                    //创建Excel文件的对象
                    var book = new HSSFWorkbook();
                    //添加一个sheet
                    var mySheet = book.CreateSheet("Sheet1");
                    //获取list数据
                    //给sheet1添加第一行的头部标题
                    var headerRow = mySheet.CreateRow(0);
                    var headerStyle = ExcelHelper.GetHeaderStyle(book);

                    var cell1 = headerRow.CreateCell(0);
                    cell1.SetCellValue("商品名称");
                    cell1.CellStyle = headerStyle;
                    mySheet.SetColumnWidth(0, 10 * 1080);


                    var cell2 = headerRow.CreateCell(1);
                    cell2.SetCellValue("唯一码");
                    cell2.CellStyle = headerStyle;
                    mySheet.SetColumnWidth(1, 10 * 1080);

                    var cell3 = headerRow.CreateCell(2);
                    cell3.SetCellValue("货品积分防伪地址");
                    cell3.CellStyle = headerStyle;
                    mySheet.SetColumnWidth(2, 10 * 1920);

                    if (modedistributor != null&& modedistributor.id > 0)
                    {
                        var cell4 = headerRow.CreateCell(3);
                        cell4.SetCellValue("经销商");
                        cell4.CellStyle = headerStyle;
                        mySheet.SetColumnWidth(3, 10 * 1080);

                    }

                    headerRow.Height = 30 * 20;
                    var commonCellStyle = ExcelHelper.GetCommonStyle(book);

                    //将数据逐步写入sheet1各个行
                    for (var i = 0; i < listModel.Count; i++)
                    {
                        var rowTemp = mySheet.CreateRow(i + 1);


                        var rowTemp0 = rowTemp.CreateCell(0);
                        rowTemp0.SetCellValue(Goods.name + ";" + ProductModel.spesDesc);
                        rowTemp0.CellStyle = commonCellStyle;


                        var rowTemp1 = rowTemp.CreateCell(1);
                        rowTemp1.SetCellValue(listModel[i].code.ToString());
                        rowTemp1.CellStyle = commonCellStyle;

                        var rowTemp2 = rowTemp.CreateCell(2);
                        rowTemp2.SetCellValue(listModel[i].url.ToString());
                        rowTemp2.CellStyle = commonCellStyle;

                        if (modedistributor != null && modedistributor.id > 0)
                        {
                            var rowTemp3 = rowTemp.CreateCell(3);
                            rowTemp3.SetCellValue(modedistributor.name);
                            rowTemp3.CellStyle = commonCellStyle;
                        }
                    }
                    // 写入到excel
                    string webRootPath = _webHostEnvironment.WebRootPath;
                    string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                    string str = Goods.name +";生成数量-" + entity.Count;
                    if (modedistributor != null && modedistributor.id > 0)
                    {
                        str += "经销商-" + modedistributor.name;
                    }
                    string fileName = str + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";
                    string filePath = webRootPath + tpath;
                    DirectoryInfo di = new DirectoryInfo(filePath);
                    if (!di.Exists)
                    {
                        di.Create();
                    }
                    FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
                    book.Write(fileHssf);
                    fileHssf.Close();

                    jm.code = 0;
                    jm.msg = GlobalConstVars.ExcelExportSuccess;
                    jm.data = tpath + fileName;
                }
                else
                {
                    jm.code = 1;
                    jm.msg = "生成失败";
                }
            }
            else
            {
                jm.code = 1;
                jm.msg = "生成数量不能小于0";

            }


            return jm;

        }

    }
}
